package org.lzy.shop.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import org.lzy.shop.base.BaseViewModel
import org.lzy.shop.response.ListSearch
import org.lzy.shop.response.SearchResponse
import org.lzy.shop.viewmodel.repository.SearchRepository
import org.lzy.shop.viewmodel.repository.lmpl.SearchRepositoryImpl

/**
 * 搜索的VM层
 */
class SearchModel() : BaseViewModel(){

    private val searchRepository: SearchRepository = SearchRepositoryImpl()
    val searchHotData = MutableLiveData<MutableList<SearchResponse>?>()
    val searchGoodsData = MutableLiveData<MutableList<ListSearch>?>()

    /**
     * 获取热门搜索关键词
     */
    fun getSearchHot(): LiveData<MutableList<SearchResponse>?> {
        viewModelScope.launch {
            try {
                val response = withTimeoutOrNull(15000) {
                    searchRepository.getSearchHot()
                } ?: throw Exception("获取热门搜索超时")

                searchHotData.value = response
            } catch (e: Exception) {
                val errorMsg = e.message ?: "获取热门搜索异常"
                errorMessage.value = errorMsg

            }
        }
        return searchHotData
    }

    /**
     * 获取搜索结果
     * @param page 页码
     * @param keyword 搜索关键词
     * @param typeIdArray 分类ID数组
     * @param orderField 排序字段
     * @param orderDirection 排序方向
     */
    fun getSearchResult(
        page: Int,
        keyword: String,
        typeId: ArrayList<Int>? = null,
        order: String = "",
        sort: String = "desc"
    ): LiveData<MutableList<ListSearch>?> {
        viewModelScope.launch {
            try {
                val response = searchRepository.getSearchResult(
                    page = page,
                    keyword = keyword,
                    typeId = typeId,
                    order = order,
                    sort = sort
                )

                if (response != null) {
                    searchGoodsData.value = response
                } else {
                    val errorMsg = "搜索结果获取失败"
                    errorMessage.value = errorMsg
                }
            } catch (e: Exception) {
                val errorMsg = e.message ?: "搜索结果获取异常"
                errorMessage.value = errorMsg
            }
        }
        return searchGoodsData
    }
}